//
//  TCVideoEditBGMHelper.m
//  TXXiaoShiPinDemo
//
//  Created by linkzhzhu on 2017/12/7.
//  Copyright © 2017年 tencent. All rights reserved.
//

#import "TCBGMHelper.h"
#import "AFHTTPSessionManager.h"
#import "pthread.h"
#import "MHMusicModel.h"

#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
//#import "TCLoginModel.h"

@interface TCBGMHelper(){
    NSDictionary* _configs;
    NSUserDefaults* _userDefaults;
    NSString* _userIDKey;
    //    NSMutableDictionary* _tasks;
    NSURLSessionDownloadTask* _currentTask;
    TCBGMElement* _currentEle;
    NSString* _bgmPath;
}
@property(nonatomic, assign)pthread_mutex_t lock;
@property(nonatomic, assign)pthread_cond_t cond;
@property(nonatomic, strong)dispatch_queue_t queue;

@property(nonatomic)NSMutableDictionary* bgmList;//只用来存储路径
@property(nonatomic,weak) id <TCBGMHelperListener>delegate;
@end

static TCBGMHelper* _sharedInstance;
static pthread_mutex_t _instanceLock = PTHREAD_MUTEX_INITIALIZER;
@implementation TCBGMHelper

+ (instancetype)sharedInstance {
    if(!_sharedInstance){
        pthread_mutex_lock(&_instanceLock);
        _sharedInstance = [TCBGMHelper new];
        pthread_mutex_unlock(&_instanceLock);
    }
    return _sharedInstance;
}

-(void) setDelegate:(nonnull id<TCBGMHelperListener>) delegate{
    _delegate = delegate;
}

-(id) init{
    if(self = [super init]){
        NSFileManager *fileManager = [NSFileManager defaultManager];
        _bgmPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/bgm"];
        if(![fileManager fileExistsAtPath:_bgmPath]){
            if(![fileManager createDirectoryAtPath:_bgmPath withIntermediateDirectories:YES attributes:nil error:nil]){
                BGMLog(@"创建BGM目录失败");
                return nil;
            }
        }
        pthread_mutex_init(&_lock, NULL);
        pthread_cond_init(&_cond, NULL);
        _userDefaults = [[NSUserDefaults alloc] initWithSuiteName:BGM_GROUP];
        if (_userDefaults == nil) {
            _userDefaults = [NSUserDefaults standardUserDefaults];
        }
        _userIDKey = [ [NSString stringWithFormat:@"%d",[MHHTTPService sharedInstance].currentUser.userId] stringByAppendingString:@"_bgm"];
        _queue = dispatch_queue_create("com.tencent.txcloud.videoedit.bgm.download", NULL);
        _bgmDict = [NSMutableDictionary new];
        NSString *bgmListPath = [NSString stringWithFormat:@"%d.tc.bgm.list",[MHHTTPService sharedInstance].currentUser.userId];
        _bgmList =   [[_userDefaults objectForKey:bgmListPath] mutableCopy];
        if (!_bgmList) {
             _bgmList = [NSMutableDictionary new];
        }
       
    }
    return self;
}

- (void)dealloc {
    pthread_mutex_destroy(&_lock);
    pthread_cond_destroy(&_cond);
}

-(void) loadBGMListFormRemoteWithPageNum:(int) pageNum pageSize:(int) pageSize finishBlock:(VoidBlock_id) finshBlock errBlock:(VoidBlock) errBlock
{
    @weakify(self);
    [[[[MHHTTPService sharedInstance] getHotSongList] mh_parsedResults] subscribeNext:^(NSArray *songs) {
        @strongify(self);

        for (TCBGMElement *model in songs) {
            TCBGMElement* ele = [self.bgmDict objectForKey:model.fullSongUrl];
//            [self.bgmList setObject:model.fullSongUrl forKey:model.fullSongUrl];
            if (ele != nil) {
                
            }else
            {
                [self saveBGMStat:model];
            }
            
        }
        
        finshBlock(songs);
        [self.delegate onBGMListLoad:self.bgmDict];
    } error:^(NSError *error) {
        errBlock();
    } completed:^{
//        finshBlock();
    }];
}


-(void) saveBGMStat:(TCBGMElement*) ele{
    [_bgmDict setObject:ele forKey:ele.fullSongUrl];
//    [_bgmList setObject:[ele fullSongUrl] forKey:[ele fullSongUrl]];
    NSData *udObject = [NSKeyedArchiver archivedDataWithRootObject:ele];
    [_userDefaults setObject:udObject forKey:[_userIDKey stringByAppendingString:[ele fullSongUrl]]];
//    [_userDefaults setObject:_bgmList forKey:[_userIDKey stringByAppendingString:@".tc.bgm.list"]];
}

-(void) downloadBGM:(TCBGMElement*) current{
    TCBGMElement* bgm = [_bgmDict objectForKey:[current fullSongUrl]];
    __block bool needOverride = true;
    //    if(bgm && [[bgm isValid] boolValue]){
    //        if(([[bgm netUrl] isEqualToString:[current netUrl]])){
    //            return;
    //        }
    //        else needOverride = false;
    //        return;
    //    }
    __weak TCBGMHelper* weak = self;
    dispatch_async(_queue, ^(){
        __strong TCBGMHelper* strong = weak;
        if(strong != nil){
            if([[_currentEle fullSongUrl] isEqualToString:[current fullSongUrl]]){
                if([_currentTask state] == NSURLSessionTaskStateRunning){
                    //                    BGMLog(@"暂停：%@", [current name]);
                    [_currentTask suspend];
                    return;
                }
                else if([_currentTask state] == NSURLSessionTaskStateSuspended){
                    //                    BGMLog(@"恢复：%@", [current name]);
                    [_currentTask resume];
                    return;
                }
            }
            else{
                if(_currentTask){
                    if([_currentTask state] != NSURLSessionTaskStateCompleted){
                        [_currentTask cancel];
                        [strong.delegate onBGMDownloading:_currentEle percent:0];
                    }
                    _currentTask = nil;
                }
            }
            NSString* localListPath = nil;
            NSString* url = [current fullSongUrl];
            
            
            __block NSString* justName = [NSString stringWithFormat:@"%@.%@",[current title],[[current fullSongUrl] pathExtension]];
            if(needOverride){
                localListPath = [_bgmPath stringByAppendingPathComponent:justName];
            }
            else{
                justName = [NSString stringWithFormat:@"%@1.%@", [justName stringByDeletingPathExtension], [[current title] pathExtension]];
                localListPath = [_bgmPath stringByAppendingPathComponent:justName];
            }
            NSURLSessionDownloadTask* task = [TCBGMHelper downloadFile:url dstUrl:localListPath callback:^(float percent, NSString* path){
                __strong TCBGMHelper* strong = weak;
                if(strong){
                    if(percent < 0){
                        dispatch_async(_queue, ^{
                            [strong.delegate onBGMDownloadDone:current];
                        });
                    }
                    else{
                        TCBGMElement* ele = [strong->_bgmDict objectForKey:[current fullSongUrl]];
                        if(path != nil){
                            ele.localUrl = [NSString stringWithFormat:@"Documents/bgm/%@", justName];
                            ele.isValid = [NSNumber numberWithBool:true];
                            dispatch_async(_queue, ^{
                                [strong.delegate onBGMDownloadDone:ele];
                                [AXAppDelegate sharedDelegate].currentSong = ele;
                            });
                            [strong saveBGMStat:ele];
                            [strong.bgmList setObject:ele.fullSongUrl forKey:ele.fullSongUrl];
                            NSString *bgmListPath = [NSString stringWithFormat:@"%d.tc.bgm.list",[MHHTTPService sharedInstance].currentUser.userId];
                            [_userDefaults setObject:strong.bgmList forKey:bgmListPath];
                            [_userDefaults synchronize];
                           NSDictionary *dic = [_userDefaults objectForKey:bgmListPath];
                        }else{
                            dispatch_async(_queue, ^{
                                [strong.delegate onBGMDownloading:ele percent:percent];
                            });
                        }
                    }
                }
            }];
            _currentTask = task;
            _currentEle = current;
        }
    });
}


-(NSArray *) loadLocalMusic
{
    
    MPMediaQuery *allMp3 = [[MPMediaQuery alloc] init];
    // 读取条件
    MPMediaPropertyPredicate *albumNamePredicate =
    [MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithInt:MPMediaTypeMusic ] forProperty: MPMediaItemPropertyMediaType];
    [allMp3 addFilterPredicate:albumNamePredicate];
    NSMutableArray *artistList = [[NSMutableArray alloc]init];
    NSArray *allMp3Items = [allMp3 items];
    for (MPMediaItem *song in allMp3Items) {
        TCBGMElement* ele =  [TCBGMElement new];
        ele.title = song.title;
        ele.artists = song.artist;
        ele.dataFromLocal = YES;
        ele.musicUrl = song.assetURL;
        NSTimeInterval secondInterVal =  song.playbackDuration;
        long seconds = lroundf(secondInterVal);
        NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
        NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
        NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
        ele.timeLength = format_time;
        MPMediaItemArtwork *artwork = [song valueForProperty: MPMediaItemPropertyArtwork];
        if (artwork) {
            ele.image = [artwork imageWithSize:CGSizeMake(50, 50)];
        }else
        {
            ele.image = [UIImage imageNamed:@"img_music_default"];
        }
        [artistList addObject:ele];
    }
    
    return [artistList copy];

}

//-(void) pauseAllTasks{
//    __weak TCBGMHelper* weak = self;
//    dispatch_async(_queue, ^(){
//        __strong TCBGMHelper* strong = weak;
//        for (id item in strong->_tasks) {
//            if([item state] == NSURLSessionTaskStateRunning)[item suspend];
//        }
//    });
//}
//
//-(void) resumeAllTasks{
//    __weak TCBGMHelper* weak = self;
//    dispatch_async(_queue, ^(){
//        __strong TCBGMHelper* strong = weak;
//        for (id item in strong->_tasks) {
//            if([item state] == NSURLSessionTaskStateSuspended)[item resume];
//        }
//    });
//}

/**
 下载函数回调
 
 @param percent 下载进度 < 0 出错并终止
 @param url 最终文件地址 nil != url则下载完成
 */
typedef void(^DownLoadCallback)(float percent, NSString* url);
+(NSURLSessionDownloadTask*) downloadFile:(NSString*)srcUrl dstUrl:(NSString*)dstUrl callback:(DownLoadCallback)callback{
    __weak __typeof(self) weakSelf = self;
    NSURLRequest *downloadReq = [NSURLRequest requestWithURL:[NSURL URLWithString:srcUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:300.f];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //注意这里progress/destination是异步线程 completionHandler是main-thread
    NSURLSessionDownloadTask* task = [manager downloadTaskWithRequest:downloadReq progress:^(NSProgress * _Nonnull downloadProgress) {
        if (callback != nil) {
            callback(downloadProgress.completedUnitCount / (float)downloadProgress.totalUnitCount, nil);
        }
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath_, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:dstUrl];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (error) {
            if(callback){
                callback(-1, nil);
            }
            return;
        }
        else{
            if(callback){
                callback(0, dstUrl);
            }
        }
    }];
    [task resume];
    return task;
}
@end


@implementation TCBGMElement


NSString *const kMHMusicModelArtists = @"artists";
NSString *const kMHMusicModelAutoId = @"autoId";
NSString *const kMHMusicModelCategoryId = @"categoryId";
NSString *const kMHMusicModelCategoryName = @"categoryName";
NSString *const kMHMusicModelCode = @"code";
NSString *const kMHMusicModelCoverUrl = @"coverUrl";
NSString *const kMHMusicModelCreated = @"created";
NSString *const kMHMusicModelDownCount = @"downCount";
NSString *const kMHMusicModelFullSongUrl = @"fullSongUrl";
NSString *const kMHMusicModelIsHaveCollect = @"isHaveCollect";
NSString *const kMHMusicModelSize = @"size";
NSString *const kMHMusicModelSongUrl = @"songUrl";
NSString *const kMHMusicModelTimeLength = @"timeLength";
NSString *const kMHMusicModelTitle = @"title";
NSString *const kMHMusicModelUserId = @"userId";

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    self.title = [aDecoder decodeObjectForKey:@"title"];
    self.isValid = [aDecoder decodeObjectForKey:@"isValid"];
    self.localUrl = [aDecoder decodeObjectForKey:@"localUrl"];
    
    self.artists = [aDecoder decodeObjectForKey:kMHMusicModelArtists];
    self.autoId = [[aDecoder decodeObjectForKey:kMHMusicModelAutoId] integerValue];
    self.categoryId = [[aDecoder decodeObjectForKey:kMHMusicModelCategoryId] integerValue];
    self.categoryName = [aDecoder decodeObjectForKey:kMHMusicModelCategoryName];
    self.code = [aDecoder decodeObjectForKey:kMHMusicModelCode];
    self.coverUrl = [aDecoder decodeObjectForKey:kMHMusicModelCoverUrl];
    self.created = [aDecoder decodeObjectForKey:kMHMusicModelCreated];
    self.downCount = [[aDecoder decodeObjectForKey:kMHMusicModelDownCount] integerValue];
    self.fullSongUrl = [aDecoder decodeObjectForKey:kMHMusicModelFullSongUrl];
    self.isHaveCollect = [[aDecoder decodeObjectForKey:kMHMusicModelIsHaveCollect] boolValue];
    self.size = [aDecoder decodeObjectForKey:kMHMusicModelSize];
    self.songUrl = [aDecoder decodeObjectForKey:kMHMusicModelSongUrl];
    self.timeLength = [aDecoder decodeObjectForKey:kMHMusicModelTimeLength];
    self.title = [aDecoder decodeObjectForKey:kMHMusicModelTitle];
    self.userId = [[aDecoder decodeObjectForKey:kMHMusicModelUserId] integerValue];
    return self;
    
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_localUrl forKey:@"localUrl"];
    [aCoder encodeObject:_title forKey:@"title"];
    [aCoder encodeObject:_isValid forKey:@"isValid"];
    if(self.artists != nil){
        [aCoder encodeObject:self.artists forKey:kMHMusicModelArtists];
    }
    [aCoder encodeObject:@(self.autoId) forKey:kMHMusicModelAutoId];    [aCoder encodeObject:@(self.categoryId) forKey:kMHMusicModelCategoryId];    if(self.categoryName != nil){
        [aCoder encodeObject:self.categoryName forKey:kMHMusicModelCategoryName];
    }
    if(self.code != nil){
        [aCoder encodeObject:self.code forKey:kMHMusicModelCode];
    }
    if(self.coverUrl != nil){
        [aCoder encodeObject:self.coverUrl forKey:kMHMusicModelCoverUrl];
    }
    if(self.created != nil){
        [aCoder encodeObject:self.created forKey:kMHMusicModelCreated];
    }
    [aCoder encodeObject:@(self.downCount) forKey:kMHMusicModelDownCount];    if(self.fullSongUrl != nil){
        [aCoder encodeObject:self.fullSongUrl forKey:kMHMusicModelFullSongUrl];
    }
    [aCoder encodeObject:@(self.isHaveCollect) forKey:kMHMusicModelIsHaveCollect];    if(self.size != nil){
        [aCoder encodeObject:self.size forKey:kMHMusicModelSize];
    }
    if(self.songUrl != nil){
        [aCoder encodeObject:self.songUrl forKey:kMHMusicModelSongUrl];
    }
    if(self.timeLength != nil){
        [aCoder encodeObject:self.timeLength forKey:kMHMusicModelTimeLength];
    }
    if(self.title != nil){
        [aCoder encodeObject:self.title forKey:kMHMusicModelTitle];
    }
    [aCoder encodeObject:@(self.userId) forKey:kMHMusicModelUserId];
}


-(BOOL) isCacheInLocal
{
    NSUserDefaults  *_userDefaults = [[NSUserDefaults alloc] initWithSuiteName:BGM_GROUP];
    if (_userDefaults == nil) {
        _userDefaults = [NSUserDefaults standardUserDefaults];
    }
    
    NSString *bgmListPath = [NSString stringWithFormat:@"%d.tc.bgm.list",[MHHTTPService sharedInstance].currentUser.userId];
    
    NSDictionary *dic =   [_userDefaults objectForKey:bgmListPath];
//       [ [NSString stringWithFormat:@"%d",[MHHTTPService sharedInstance].currentUser.userId] stringByAppendingString:@"_bgm"]
    //    [_userDefaults setObject:_bgmList forKey:[_userIDKey stringByAppendingString:@".tc.bgm.list"]];
    
//    NSString *cachePatch = [[[NSString stringWithFormat:@"%d",[MHHTTPService sharedInstance].currentUser.userId] stringByAppendingString:@"_bgm"] stringByAppendingString:self.fullSongUrl];
    

    
//    TCBGMElement* ele = [NSKeyedUnarchiver unarchiveObjectWithData:[_userDefaults objectForKey:[[ [NSString stringWithFormat:@"%d",[MHHTTPService sharedInstance].currentUser.userId] stringByAppendingString:@"_bgm"] stringByAppendingString:self.fullSongUrl]]];
    return [dic containsObjectForKey:self.fullSongUrl];
}

@end
